import 'dart:async';
import 'dart:ui';

import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/order_list_entity.dart';
import 'package:factoryside/generated/json/order_list_entity_helper.dart';
import 'package:factoryside/utils/ColorsUtils.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/widget/jh_login_textfield.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'page_order.dart';

///工单搜索页面

class SearchOrderPage extends StatefulWidget {
  @override
  _SearchOrderPageState createState() => _SearchOrderPageState();
}

class _SearchOrderPageState extends State<SearchOrderPage>
    with AutomaticKeepAliveClientMixin {
  var page = 1;
  var limit = 10;
  String search = '';
  TextEditingController searchCtr = TextEditingController();
  var items = [];
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  void _fetchData() {
    RequestUtil.post(Api.getOrderList,{
      'State':'5',
      'Search':search,
      'page':page,
      'limit':limit
    }).then((value){
      List list=value['Data']['data'];
      List<OrderListEntity> tempList=[];
      list.forEach((element) {
        tempList.add(orderListEntityFromJson(OrderListEntity(),element));
      });
      if (page == 1) {
        items=tempList;
        _refreshController.resetNoData();
      } else {
        if (tempList.length == 0) {
          _refreshController.loadNoData();
        } else {
          items.addAll(tempList);
        }
      }
      if (mounted) {
        setState(() {

        });
      }
    });
  }

  @override
  void dispose() {
    print('dispose');
    _refreshController.dispose();
    super.dispose();
  }

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1000));

    _fetchData();
    _refreshController.resetNoData();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    await Future.delayed(Duration(microseconds: 1000));

    page++;
    _fetchData();
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); //必须实现 不然 在push过后页面会刷新
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          brightness: Brightness.light,
          title: Container(
            margin: EdgeInsets.only(left: 10),
//            padding: EdgeInsets.symmetric(horizontal: 5),
            decoration: new BoxDecoration(
//              border: Border.all(color: Colors.white, width: 1.0), //灰色的一层边框
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(5.0)),
            ),
            alignment: Alignment.center,
            height: 38,
//           padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
            child: JhLoginTextField(
              controller: searchCtr,
//              leftWidget: Icon(Icons.search,size: 25,),
              hintText: '工单号、客户手机号',
              isShowDeleteBtn: true,
              isDense: true,
              border: OutlineInputBorder(
                  /*边角*/
                  borderRadius: BorderRadius.all(
                    Radius.circular(5),
                  ),
                  borderSide: BorderSide(
                    color: Colors.grey, //边线颜色
                    width: 0.2, //边线宽度
                  )),
              inputCallBack: (keyword) {
                search = keyword;
                _fetchData();
              },
            ),
          ),
          titleSpacing: 0,
          actions: [
            TextButton(
              child: Text(
                '取消',
                style: TextStyle(color: Colors.blue),
              ),
              onPressed: () {
                Navigator.pop(context);
              },
            )
          ],
          automaticallyImplyLeading: false, //隐藏返回箭头
//          leading: IconButton(
//            icon: Icon(Icons.arrow_back_ios, color: Colors.white), //自定义图标
//            onPressed: () {
//              Navigator.pop(context);
//            },
//          ),
          elevation: 0.1,
//          brightness: Brightness.light,
        ),
        body: Container(
          color: ColorsUtil.hexToColor('#F2F2F2'),
//    padding: EdgeInsets.only(top: 10),
          child: items.length == 0
              ? buildSmartRefresher(buildEmptyContainer())
              : buildSmartRefresher(ListView.builder(
                  itemBuilder: (context, i) {
                    return OrderCell(index: i,order: items[i], c: context);
                  },
                  itemCount: items.length,
                )),
        ));
  }

  Container buildEmptyContainer() {
    return Container(
      color: Colors.white,
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset(
              'assets/v3_nodata.png',
              width: 100,
              height: 100,
            ),
            Text(
              '暂无工单',
              style: TextStyle(color: Colors.grey),
            ),
          ],
        ),
      ),
    );
  }

  SmartRefresher buildSmartRefresher(Widget child) {
    return SmartRefresher(
      enablePullDown: true,
      enablePullUp: items.length != 0,
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: child,
    );
  }

  @override
  bool get wantKeepAlive => true;
}
